<template>
  <el-dialog
    :title="
      !dataForm.userId
        ? i18n['gobal.button.insert']
        : i18n['gobal.button.update']
    "
    :close-on-click-modal="false"
    width="30%"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item
        :label="i18n['sys.user.field.loginName.title']"
        prop="loginName"
      >
        <el-input
          v-model="dataForm.loginName"
          maxlength="64"
          :placeholder="i18n['sys.user.field.loginName.title']"
        ></el-input>
      </el-form-item>

      <el-form-item
        :label="i18n['sys.user.field.userName.title']"
        prop="userName"
      >
        <el-input v-model="dataForm.userName" maxlength="64"></el-input>
      </el-form-item>

      <div v-if="isAppend">
        <el-form-item
          :label="i18n['sys.user.field.password.title']"
          prop="password"
          :class="{ 'is-required': !dataForm.userId }"
        >
          <el-input
            v-model="dataForm.password"
            type="Password"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item :label="i18n['sys.user.field.phone.title']" prop="phone">
        <el-input v-model="dataForm.phone" maxlength="64"></el-input>
      </el-form-item>

      <el-form-item
        :label="i18n['sys.user.field.roleIdList.title']"
        size="mini"
        prop="roleIdList"
      >
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleId"
            >{{ role.roleName }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        :label="i18n['gobal.field.defaultFlag']"
        size="mini"
        prop="disableFlag"
      >
        <el-radio-group v-model="dataForm.disableFlag">
          <el-radio :label="0">{{
            i18n["gobal.field.defaultFlag.NO"]
          }}</el-radio>
          <el-radio :label="1">{{
            i18n["gobal.field.defaultFlag.YES"]
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{
        i18n["gobal.button.cancel"]
      }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{
        i18n["gobal.button.ok"]
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { encryptPassword } from "@/utils";
import { isLoginName, isLoginPassword } from "@/utils/validate";
export default {
  inject: ["i18n"],
  data() {
    var validateLoginName = (rule, value, callback) => {
      if (value && !isLoginName(value)) {
        callback(new Error(i18n["user.valid.loginName.incorrect"]));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.userId && value && !isLoginPassword(value)) {
        callback(new Error(i18n["user.valid.password.incorrect"]));
      } else {
        callback();
      }
    };
    return {
      isAppend: false,
      visible: false,
      roleList: [],
      dataForm: {
        userId: 0,
        userName: "",
        loginName: "",
        password: "",
        phone: "",
        roleIdList: [],
        disableFlag: 1,
      },
      dataRule: {
        loginName: [
          {
            required: true,
            message: i18n["user.valid.loginName.not-null"],
            trigger: "blur",
          },
          { validator: validateLoginName, trigger: "blur" },
        ],
        userName: [
          {
            required: true,
            message: i18n["user.valid.userName.not-null"],
            trigger: "blur",
          },
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    init(userId) {
      this.$http({
        url: this.$http.adornUrl("/sys/role/select"),
        method: "post",
        data: this.$http.adornData(),
      })
        .then(({ data }) => {
          this.roleList = data && data.code === 200 ? data.data : [];
        })
        .then(() => {
          this.visible = true;
          this.isAppend = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          this.dataForm.userId = userId || 0;
          if (this.dataForm.userId) {
            this.isAppend = false;
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info`),
              method: "post",
              data: this.$http.adornData({ key: this.dataForm.userId }),
            }).then(({ data }) => {
              if (data && data.code === 200) {
                // 登录名
                this.dataForm.loginName = data.data.loginName;
                this.dataForm.userName = data.data.userName;
                this.dataForm.phone = data.data.phone;
                this.dataForm.roleIdList = data.data.roleIdList;
                this.dataForm.disableFlag = data.data.disableFlag;
              }
            });
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/user/${!this.dataForm.userId ? "insert" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              userId: this.dataForm.userId || undefined,
              loginName: this.dataForm.loginName,
              password: encryptPassword(this.dataForm.password),
              userName: this.dataForm.userName,
              phone: this.dataForm.phone,
              disableFlag: this.dataForm.disableFlag,
              roleIdList: this.dataForm.roleIdList,
            }),
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: i18n["gobal.hint.succeeded"],
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
